package hxvid;
using hxvid.Logger;
class Logger
{
	public var path:String;
	public var id:String;
	public var enabled:Bool;
	public var errorEnabled:Bool;
	public var console:Bool;
	public var trace:Dynamic;
	private static inline var ld = "[";
	private static inline var rd = "] ";
	public function new(?path:String="log.txt")
	{
		this.path = path;
		this.id="";
		this.enabled = true;
		this.errorEnabled = true;
		this.console = true;
		this.trace = this.info;
	}
	public function error(e:Dynamic,?p:haxe.PosInfos)
	{
		if(errorEnabled)
		{
			var str = ld + "ERROR" + rd +idts(p) +  (try Std.string(e) catch( e : Dynamic ) "e.toString() failed");
			var stack = haxe.Stack.exceptionStack();
			var out = str + haxe.Stack.toString(stack) + "\n";
			if(console) neko.Lib.print(out);
			append(out);
		}
	}
	public function warning(msg:Dynamic,?p:haxe.PosInfos)
	{
		if(enabled)
		{
			var out = ld+ "WARNING" + rd +idts(p) +  msg + "\n";
			if(console) neko.Lib.print(out);
			append(out);
		}
	}
	public function info(msg:Dynamic,?p:haxe.PosInfos)
	{
		if(enabled)
		{
			var out = ld + "INFO" + rd +idts(p) +  msg + "\n";
			if(console) neko.Lib.print(out);
			append(out);
		}
	}
	public function debug(msg:Dynamic,?p:haxe.PosInfos)
	{
		if(enabled)
		{
			var out = ld+"DEBUG"+rd +idts(p) +  msg + "\n";
			if(console) neko.Lib.print(out);
			append(out);
		}
	}
	public function command(msg:String,?p:haxe.PosInfos)
	{
		if(enabled)
		{
			var out = ld + "COMMAND"+rd +idts(p) +  msg + "\n";
			if(console) neko.Lib.print(out);
			append(out);
		}
	}
	private function append(msg:String)
	{
		if(path==null)
			return;
		var fOut = neko.io.File.append(path, false);
		fOut.writeString(msg);
		fOut.close();
	}
	inline function idts(?p:Dynamic=null):String
	{
		var date = ld + Date.now().toString() + rd;
		var posA = (p!=null) ? (ld+p.fileName +":" +p.className+":"+p.methodName+":"+p.lineNumber+rd) : ("");
		var posB = (p!=null) ? (ld+p.fileName +":"+p.lineNumber+" "+p.methodName+rd) : ("");
		var id = ld + id + rd;
		return  date + id + posB ;
	}
}